import Dialog from '@vant/weapp/dialog/dialog'
import { getCookies, remove } from '@/utils/cookies'
import Toast from '@vant/weapp/toast/toast'
const app = getApp()
Page({
  data: {
    id: getCookies('id'),
    api: app.globalData.api,
    name: getCookies('name'),
    imgUrl: 0,
    isAvatar: false,
    fileList: []
  },
  onLoad() {
    this.setData({ name: getCookies('name') })
  },
  showUpdateAvatar(){
    if (!getCookies('id')) {
      Toast.fail({ message: '您还未登录呢', context: this })
      return 
    }
    this.setData({ isAvatar: true })
  },
  closeUpdateAvatar(){
    this.setData({ isAvatar: false })
  },
  afterRead(event) {
    const that = this
    const { file } = event.detail;
    wx.uploadFile({
      url: this.data.api + 'user/uploadImage',
      filePath: file.url,
      name: 'file',
      formData: { id: this.data.id},
      header:{
        'token': getCookies('token')
      },
      success(res) {
        Toast.success({ message: '上传头像成功', context: that })
        that.setData({ isAvatar: false, imgUrl: Math.random() })
      },
      fail(err) {
        Toast.fail({ message: '上传头像失败', context: this })
      }
    });
  },
  goOrder(event) {
    wx.switchTab({
      url: '/pages/indent/index',
    success(e) {
        const page = getCurrentPages().pop();
        if (page == undefined || page == null || page.route !== "pages/indent/index") return
        page.onLoadOrder(event.currentTarget.dataset.idx)
      }
    })
  },
  updatePassword() {
    if (!getCookies('id')) {
      Toast.fail({ message: '您还未登录呢', context: this })
      return 
    }
    wx.navigateTo({
      url:"/layout/user/update/index"
    })
  },
  updateInfo() {
    if (!getCookies('id')) {
      Toast.fail({ message: '您还未登录呢', context: this })
      return 
    }
    wx.navigateTo({
      url: "/layout/user/updateInfo/index"
    })
  },
  outLogin() {
    if (!getCookies('id')) {
      Toast.fail({ message: '您还未登录呢', context: this })
      return 
    }
    Dialog.confirm({
      title: '提醒',
      message: '您确认退出当前账号吗？',
    }).then(() => {
        remove()
        let timer = setTimeout(() => {
          clearTimeout(timer)
          Toast.success({ message: '退出成功', context: this })
          this.onLoad()
        })
      }).catch(() => {
        
      });
  },
  onShow() {
    this.setData({ id: getCookies('id'), imgUrl: Math.random() })
  }
})